package com.cormant.plugin.locationplugin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;

import android.location.Location;

import com.cormant.citracker.CILocationListener;

public class LocationPlugin extends CordovaPlugin {

	public LocationPlugin() {
	}

	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) {

		if (action.equals("location")) {
			JSONArray result = new JSONArray(buildLocList());
			callbackContext.success(result);
			return true;
		} else if (action.equals("clear")) {
			CILocationListener.getInstance().getLocations().clear();
			callbackContext.success(new JSONArray(new ArrayList<String>()));
			return true;
		}
		return false;
	}

	private List<String> buildLocList() {
		List<String> coords = new ArrayList<String>();
		List<Location> locations = CILocationListener.getInstance()
				.getLocations();

		for (int i = 0; i < locations.size(); i++) {
			coords.add(locations.get(i).getLatitude() + ", "
					+ locations.get(i).getLongitude());
		}

		return coords;
	}

	private List<Coordinate> buildCoordsList() {
		List<Coordinate> coords = new ArrayList<Coordinate>();
		List<Location> locations = CILocationListener.getInstance()
				.getLocations();

		for (int i = 0; i < locations.size(); i++) {
			coords.add(new Coordinate(locations.get(i).getLatitude(), locations
					.get(i).getLongitude()));
		}

		// return coords;
		return Arrays.asList(new Coordinate(14.5498065, 121.0457386),
				new Coordinate(14.5498065, 121.111111), new Coordinate(
						14.5498065, 121.1457386));
	}

	private class Coordinate {
		private double x;
		private double y;

		public Coordinate(double x, double y) {
			this.x = x;
			this.y = y;
		}

		public double getX() {
			return x;
		}

		public void setX(double x) {
			this.x = x;
		}

		public double getY() {
			return y;
		}

		public void setY(double y) {
			this.y = y;
		}
	}

}